<?php

namespace App\Http\Controllers\Template;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Template\TemplateContractsStamp as TemplateTemplateContractsStamp;
use App\Models\Template\TemplateContractsStamp;
use Illuminate\Http\Request;

/**
 * 合同模版
 */
class TemplateContractsStampController extends BaseController
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;


        $list = TemplateContractsStamp::getList($request, $this->mangerinfo['cpid'], $status, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 新增合同模版
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['contracts_no', 'company_id',  'seal_filepath']);

        $Validate = new TemplateTemplateContractsStamp();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        // 检查合同编号是否已存在
        $contractExists = TemplateContractsStamp::query()
            ->where('cpid', $this->mangerinfo['cpid'])
            ->where('contracts_no', $req_data['contracts_no'])
            ->exists();

        if ($contractExists) {
            return response()->json(['code' => '001', 'msg' => '合同编码不允许重复']);
        }

        // 检查结算公司是否已存在且状态为启用
        $companyExists = TemplateContractsStamp::query()
            ->where('cpid', $this->mangerinfo['cpid'])
            ->where('company_id', $req_data['company_id'])
            ->where('status', 1)
            ->exists();

        if ($companyExists) {
            return response()->json(['code' => '001', 'msg' => '结算公司重复']);
        }


        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'contracts_no' => $req_data['contracts_no'],
            'company_id' => $req_data['company_id'],
            'seal_filepath' => $req_data['seal_filepath'],
            'update_at' => time()
        ];
        $data['create_at'] = time();
        TemplateContractsStamp::create($data)->id;

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {
        $id = $request->id ?? 0;
        $info = TemplateContractsStamp::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        TemplateContractsStamp::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
